package com.xwm93up.guavalimit;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @Description: desc
 * @Author: xwm93up
 * @Since: 2021/10/25 18:10
 */
@Slf4j
@RestController
@RequestMapping("/limit")
public class LimitController {
    /**
     * 限流策略,一秒钟一个请求
     */
    private final RateLimiter limiter = RateLimiter.create(1.0);
    private DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @RequestMapping("/test1")
    public String testLimiter() {
        // 500毫秒内没有拿到令牌, 就直接进入服务降级
        boolean tryAcquire = limiter.tryAcquire(500, TimeUnit.MILLISECONDS);
        if (!tryAcquire) {
            log.warn("进入服务降级, 时间{}", LocalDateTime.now().format(dft));
            return "当前排队人数较多, 请稍后再试!";
        }
        log.info("获取令牌成功,时间{}", LocalDateTime.now().format(dft));
        return "请求成功";
    }


    @GetMapping("/test2")
    @Limit(key = "limit2", permitsPerSecond = 1, timeout = 500, timeunit = TimeUnit.MILLISECONDS, msg = "当前排队人数较多，请稍后再试！")
    public String limit2() {
        log.info("令牌桶limit2获取令牌成功");
        return "ok";
    }


    @GetMapping("/test3")
    @Limit(key = "limit3", permitsPerSecond = 2, timeout = 500, timeunit = TimeUnit.MILLISECONDS, msg = "系统繁忙，请稍后再试！")
    public String limit3() {
        log.info("令牌桶limit3获取令牌成功");
        return "ok";
    }
}
